package com.code.man.view;

import com.code.man.CodeGenerator;
import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import com.intellij.ide.util.PackageChooserDialog;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.psi.PsiPackage;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * 代码生成配置表单窗口
 *
 * @author devinpzhang
 * @date 2019/9/26 20:29
 */
public class GenerateConfigForm extends JDialog {
    public JPanel mainPanel;
    public JCheckBox cbController;
    public JCheckBox cbServiceImpl;
    public JCheckBox cbService;
    public JButton btnGenerate;
    private JButton btnClose;
    private JCheckBox cbMapper;
    private JCheckBox cbMapperXml;
    private JTextField txtTables;
    private JCheckBox cbEntity;
    private JTextField txtPackage;
    private JTextField txtOutputPath;
    private JButton packageChooseButton;
    private JButton pathChooseButton;

    private Project project;
    private String projectPath;
    private CodeGenerator generator = null;

    public GenerateConfigForm(Project project) {
        this.project = project;
        this.projectPath = project.getBasePath();

        setContentPane(mainPanel);
        setModal(true);
        setSize(720,450);
        getRootPane().setDefaultButton(btnGenerate);

        btnGenerate.addActionListener(e -> onOK());

        btnClose.addActionListener(e -> onCancel());

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        mainPanel.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

        init();
    }

    /**
     * 确认按钮回调
     */
    private void onOK() {
        try {
            String outputPath = txtOutputPath.getText().trim();
            if (StringUtils.isBlank(outputPath)) {
                Messages.showWarningDialog("output path不能为空!", "提示信息");
                return;
            }

            String tables = txtTables.getText().trim();
            if (StringUtils.isBlank(tables)) {
                Messages.showWarningDialog("表名称不能为空!", "提示信息");
                return;
            }

            //每次开始生成代码时，重新加载并设置参数
            generator.loadXmlConfig();
            generator.getConfig().setOutputPath(txtOutputPath.getText());
            generator.getConfig().setGeneratePackage(txtPackage.getText());
            generator.getConfig().setTables(Sets.newHashSet(tables.split(",")));

            generator.getConfig().setControllerChecked(cbController.isSelected());
            generator.getConfig().setServiceChecked(cbService.isSelected());
            generator.getConfig().setServiceImplChecked(cbServiceImpl.isSelected());
            generator.getConfig().setEntityChecked(cbEntity.isSelected());
            generator.getConfig().setMapperChecked(cbMapper.isSelected());
            generator.getConfig().setMapperXmlChecked(cbMapperXml.isSelected());

            //生成代码
            generator.generate();
            Messages.showMessageDialog("代码生成完成", "提示信息", Messages.getInformationIcon());

            //关闭窗口
            dispose();

            //刷新整个项目
            VirtualFileManager.getInstance().syncRefresh();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 取消按钮回调
     */
    private void onCancel() {
        dispose();
    }

    /**
     * 打开窗口
     */
    public void open() {
        setTitle("代码生成工具 - 跨越侠");
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void init(){
        generator = new CodeGenerator(projectPath);
        generator.loadXmlConfig();

        //默认的输出路径
        if (StringUtils.isBlank(generator.getConfig().getOutputPath())) {
            generator.getConfig().setOutputPath(projectPath);
        }

        this.txtOutputPath.setText(generator.getConfig().getOutputPath());
        this.txtPackage.setText(generator.getConfig().getGeneratePackage());
        this.txtTables.setText(Joiner.on(',').join(generator.getConfig().getTables()));

        this.cbController.setSelected(true);
        this.cbService.setSelected(true);
        this.cbServiceImpl.setSelected(true);
        this.cbEntity.setSelected(true);
        this.cbMapper.setSelected(true);
        this.cbMapperXml.setSelected(true);

        //添加输出路径选择事件
        pathChooseButton.addActionListener(e -> {
            //将当前选中的项目设置为基础路径
            VirtualFile path = project.getProjectFile().getParent().getParent();

            VirtualFile virtualFile = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFolderDescriptor(),project, path);
            if (virtualFile != null) {
                txtOutputPath.setText(virtualFile.getPath());
            }
        });

        //添加包选择事件
        packageChooseButton.addActionListener(e -> {
            PackageChooserDialog dialog = new PackageChooserDialog("Package Chooser", project);
            dialog.show();
            PsiPackage psiPackage = dialog.getSelectedPackage();
            if (psiPackage != null) {
                txtPackage.setText(psiPackage.getQualifiedName());
            }
        });
    }
}
